//  @ Project : SPPager
//  @ File Name : SPRepository.cs
//  @ Date : 2013/6/5
//  @ Author : yubaolee(.cpp)
//  @ Description: 

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
namespace LYB.NET.SPPager
{
    public class SPRepository : IRepository
    {
        readonly StoredProcedureBase _sqlbase;
        public SPRepository(StoredProcedureBase sql)
        {
            _sqlbase = sql;
        }
        public  PageList<T> GetList<T>(int pageindex, int pagesize)
        {
            IList<T> pList = new List<T>();
            SqlDataReader reader = _sqlbase.GetDataReader(pageindex, pagesize);
            while (reader.Read())
            {
                //you must use Activator.CreateInstance<T>() to create object by type of T, because you don't know the type.
                T rowInstance = Activator.CreateInstance<T>();
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    try
                    {
                        int ordinal = reader.GetOrdinal(property.Name);
                        if (reader.GetValue(ordinal) != DBNull.Value)
                        {
                            //set RowInstance value with SqlDataReader
                            property.SetValue(rowInstance, Convert.ChangeType(reader.GetValue(ordinal), property.PropertyType), null);
                        }
                    }
                    catch
                    {
                        break;
                    }
                }
                //fill to pList
                pList.Add(rowInstance);
            }
            reader.Close();
            return new PageList<T>(pList, pagesize, pageindex, _sqlbase.TotalRecordCount);
        }
    }
}
